import Vue from 'vue'
import { Loading } from 'element-ui'
import store from '../store'
import router from '../router/router'
import CryptoJS from 'crypto-js'
import Cookies from 'js-cookie'

export const isEmpty = (val) => {
  if (
    val === null ||
    val === undefined ||
    typeof val === 'undefined' ||
    (typeof val === 'string' && val === '' && val !== 'undefined')
  ) {
    return true
  }
  return false
}

export const getUrlKey = (name, url) => {
  return (
    decodeURIComponent(
      (new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(url) || [, ''])[1].replace(/\+/g, '%20')
    ) || null
  )
}

//表单序列化
export const serialize = (data) => {
  let list = []
  Object.keys(data).forEach((ele) => {
    list.push(`${ele}=${data[ele]}`)
  })
  return list.join('&')
}

export const getObjType = (obj) => {
  var toString = Object.prototype.toString
  var map = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object'
  }
  if (obj instanceof Element) {
    return 'element'
  }
  return map[toString.call(obj)]
}
/**
 * 对象深拷贝
 */
export const deepClone = (data) => {
  var type = getObjType(data)
  var obj
  if (type === 'array') {
    obj = []
  } else if (type === 'object') {
    obj = {}
  } else {
    //不再具有下一层次
    return data
  }
  if (type === 'array') {
    for (var i = 0, len = data.length; i < len; i++) {
      obj.push(deepClone(data[i]))
    }
  } else if (type === 'object') {
    for (var key in data) {
      obj[key] = deepClone(data[key])
    }
  }
  return obj
}

// 压缩图片
export const compressImg = (file, fileName, config) => {
  const read = new FileReader()
  read.readAsDataURL(file)
  return new Promise(function (resolve, reject) {
    read.onload = function (e) {
      let img = new Image()
      img.src = e.target.result
      img.onload = function () {
        // 默认按比例压缩
        let w
        let h
        if (img.height > img.width) {
          w = config.size * (img.width / img.height)
          h = config.size
        } else {
          w = config.size
          h = config.size * (img.height / img.width)
        }

        // 生成canvas
        let canvas = document.createElement('canvas')
        let ctx = canvas.getContext('2d')
        let base64
        canvas.setAttribute('width', w)
        canvas.setAttribute('height', h)
        ctx.drawImage(this, 0, 0, w, h)

        base64 = canvas.toDataURL(file['type'], config.quality)

        let fileBinary = dataURLtoFile(base64, fileName)

        resolve(fileBinary)
      }
    }
  })
}

// base64转码（将base64编码转回file文件）  此方法我没用到
function dataURLtoFile(dataurl, fileName) {
  let arr = dataurl.split(',')
  let mime = arr[0].match(/:(.*?);/)[1]
  let bstr = atob(arr[1])
  let n = bstr.length
  let u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], fileName, { type: mime })
}

let myLoading = null

export function showLoading(text) {
  setTimeout(() => {
    myLoading = Loading.service({
      lock: true,
      text: text ? text : '正在加载',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.5)'
    })

    setTimeout(() => {
      if (myLoading) {
        myLoading.close()
      }
    }, 60000)
  }, 10)
}

export function hideLoading() {
  if (myLoading) {
    myLoading.close()
  }
}

function getTplValueById(data, id, type) {
  if (!data || !data.objectValues) {
    if (type === 1) {
      return ''
    } else {
      return { list: [] }
    }
  }

  let retStr = ''
  let retStrArr = []
  for (let index = 0; index < data.objectValues.length; index++) {
    const element = data.objectValues[index]
    if (element.attributeId === id) {
      retStr = element.attributeValue
      retStrArr.push(element.attributeValue)
    }
  }

  if (type === 1) {
    return retStr
  } else {
    return { list: retStrArr }
  }
}

export const trim = (str) => {
  return str.replace(/(^\s*)|(\s*$)/g, '')
}

export const groupBy = (array, f) => {
  const groups = {}
  array.forEach(function (o) {
    const group = f(o)
    groups[group] = groups[group] || []
    groups[group].push(o)
  })
  return Object.keys(groups).map(function (group) {
    const item = {
      name: group,
      list: groups[group]
    }
    return item
  })
}

export const urlParamStr = (data) => {
  if (!data) {
    return ''
  } else {
    let paramStr = ''
    Object.keys(data).forEach((key) => {
      if (!paramStr) {
        paramStr = '?' + key + '=' + data[key]
      } else {
        paramStr = paramStr + '&' + key + '=' + data[key]
      }
    })

    return paramStr
  }
}

var lut = []
for (var i = 0; i < 256; i++) {
  lut[i] = (i < 16 ? '0' : '') + i.toString(16)
}

export const padLeftZero = (str) => {
  return ('00' + str).substr(str.length)
}

export const drawLine = (context, x1, y1, x2, y2) => {
  context.moveTo(x1, y1)
  context.lineTo(x2, y2)
  context.stroke()
}

export const drawCircle = (context, x1, y1, size) => {
  context.beginPath()
  context.arc(x1, y1, size, 0, 2 * Math.PI)
  context.fillStyle = '#00CFA5'
  context.fill()
  context.stroke()
}

export const uploadFile = (url, file, fileType, callback) => {
  if (!file) {
    return
  }

  let param = new FormData()
  param.append('file', file)
  param.append('fileType', fileType)

  let config = {
    headers: {
      'Content-Type': 'multipart/form-data',
      Authorization: 'bearer ' + store.state.common.token
    }
  }

  axios
    .post(url, param, config)
    .then((res) => {
      const status = res.data ? res.data.code : ''
      const message = res.data.message || res.data.msg || '服务器出错，请稍后尝试！'

      if (status !== 200) {
        Vue.$toast(message, {
          type: 'error'
        })
      }

      if (callback) {
        callback(res.data)
      }
    })
    .catch((e) => {
      if (callback) {
        callback(e)
      }
    })
}

export const isNumberByGe0 = (val) => {
  if (val === 0) {
    return true
  }

  if (!val) {
    return false
  }

  if (!(val + ' ').trim()) {
    return false
  }

  if (isNaN(val)) {
    return false
  }

  if (val < 0) {
    return false
  }

  return true
}

export const ciphertext = (text) => {
  if (!text) {
    return ''
  } else {
    return (text + '').replace(/^(\d{3})(\d{4})\d+/, '$1$2****')
  }
}

export const dateFormat = (dateValue, format) => {
  if (!dateValue) {
    return ''
  }

  let date
  if (typeof dateValue === 'object') {
    date = dateValue
  } else {
    if (typeof dateValue === 'string') {
      dateValue = dateValue.replace('-', '/')
      dateValue = dateValue.replace('-', '/')
      date = new Date(dateValue)
    } else {
      date = new Date(dateValue)
    }
  }

  let o = {
    'M+': date.getMonth() + 1, //month
    'd+': date.getDate(), //day
    'h+': date.getHours(), //hour
    'm+': date.getMinutes(), //minute
    's+': date.getSeconds(), //second
    'q+': Math.floor((date.getMonth() + 3) / 3), //quarter
    S: date.getMilliseconds() //millisecond
  }

  const re = /(y+)/
  if (re.test(format)) {
    const t = re.exec(format)[1]
    format = format.replace(t, (date.getFullYear() + '').substring(4 - t.length))
  }

  for (let k in o) {
    const regx = new RegExp('(' + k + ')')
    if (regx.test(format)) {
      const t = regx.exec(format)[1]
      format = format.replace(t, t.length == 1 ? o[k] : ('00' + o[k]).substring(('' + o[k]).length))
    }
  }

  return format
}

export const logout = () => {
  store.dispatch('setToken', '')
  store.dispatch('setIsLogin', false)
  store.dispatch('setAccountId', '')
  store.dispatch('setAccount', '')
  store.dispatch('setNickname', '')
  store.dispatch('setEmail', '')
  store.dispatch('setPointLeft', 0)
  store.dispatch('setRealnameState', '')
  store.dispatch('setRealnameInfo', {})
  store.dispatch('setCurAdminType', '')

  const path = router.app._route.path

  if (path.indexOf('/user') !== -1) {
    if (
      !(path.indexOf('/search/resource/flowDetail') !== -1) &&
      !(path.indexOf('/search/resource/pageDetail') !== -1) &&
      !(path.indexOf('/search/resource/documentDetail') !== -1)
    ) {
      router.replace('/')
    }
  }
}

export const isPhoneNo = (s) => {
  return /^1[3456789]\d{9}$/.test(s)
}

export const isEmailNo = (s) => {
  return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(s)
}

export const isIdCardNo = (value) => {
  var sId = value
  if (sId.length == 15) {
    if (!/^\d{14}(\d|x)$/i.test(sId)) {
      return false
    } else {
      sId = sId.substr(0, 6) + '19' + sId.substr(6, 9)
      sId += getVCode(sId)
    }
  }

  function getVCode(CardNo17) {
    var Wi = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1)
    var Ai = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2')
    var cardNoSum = 0
    for (var i = 0; i < CardNo17.length; i++) cardNoSum += CardNo17.charAt(i) * Wi[i]
    var seq = cardNoSum % 11
    return Ai[seq]
  }

  var aCity = {
    11: '北京',
    12: '天津',
    13: '河北',
    14: '山西',
    15: '内蒙古',
    21: '辽宁',
    22: '吉林',
    23: '黑龙江',
    31: '上海',
    32: '江苏',
    33: '浙江',
    34: '安徽',
    35: '福建',
    36: '江西',
    37: '山东',
    41: '河南',
    42: '湖北',
    43: '湖南',
    44: '广东',
    45: '广西',
    46: '海南',
    50: '重庆',
    51: '四川',
    52: '贵州',
    53: '云南',
    54: '西藏',
    61: '陕西',
    62: '甘肃',
    63: '青海',
    64: '宁夏',
    65: '新疆',
    71: '台湾',
    81: '香港',
    82: '澳门',
    91: '国外'
  }

  var iSum = 0
  if (!/^\d{17}(\d|x)$/i.test(sId)) {
    return false
  }
  sId = sId.replace(/x$/i, 'a')
  if (aCity[parseInt(sId.substr(0, 2))] == null) {
    return false
  }
  var sBirthday = sId.substr(6, 4) + '-' + Number(sId.substr(10, 2)) + '-' + Number(sId.substr(12, 2))
  var d = new Date(sBirthday.replace(/-/g, '/'))
  if (sBirthday != d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate()) {
    return false
  }
  for (var i = 17; i >= 0; i--) iSum += (Math.pow(2, i) % 11) * parseInt(sId.charAt(17 - i), 11)
  if (iSum % 11 != 1) {
    return false
  }
  return true
}

export const isAllNumber = (str) => {
  const reg = /^[0-9]*$/
  return reg.test(str)
}

export const fileNameFromUrl = (fileName, andType) => {
  if (!fileName) {
    return ''
  }

  let arr = fileName.split('/')

  if (andType) {
    return arr[arr.length - 1]
  } else {
    let lastItem = arr[arr.length - 1]
    let lastItemArr = lastItem.split('.')
    return lastItemArr[0]
  }
}

//登录信息的cookie的超时时间为2天
export const getLoginedExpiresTime = () => {
  const millisecond = new Date().getTime()
  return new Date(millisecond + 172800000)
}

export const aesEncrypt = (word, keyWord = 'XwKsGlMcdPMEhR1B') => {
  var key = CryptoJS.enc.Utf8.parse(keyWord)
  var srcs = CryptoJS.enc.Utf8.parse(word)
  var encrypted = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })
  return encrypted.toString()
}

/**
 * 在新页面中打开连接
 * @param path 路由地址
 * @param params 参数
 */
export const pushByNewPage = (path, params) => {
  if (!path) {
    return
  }

  let url = window.location.origin + path
  if (params) {
    url = url + '?'
    Object.keys(params).forEach((key, idx) => {
      if (idx === 0) {
        url = url + key + '=' + params[key]
      } else {
        url = url + '&' + key + '=' + params[key]
      }
    })
  }
  window.open(url, '_blank')
}

export const upToInt = (value) => {
  if (!value) {
    return 0
  }

  let theValue = value + ''
  let retValue = '1'

  for (let index = 0; index < theValue.length; index++) {
    retValue = retValue + '0'
  }

  return parseInt(retValue)
}

export const startsWith = (str, prefix) => {
  if (!str || !prefix) {
    return false
  }

  if (str.trim().length === 0 || prefix.trim().length === 0) {
    return false
  }

  return checkRange(str, prefix, 0)
}

export const checkRange = (str, substr, start) => {
  return substr === '' || (str.length >= substr.length && str.substr(start, start + substr.length) === substr)
}

export default {
  isEmpty,
  getUrlKey,
  compressImg,
  getTplValueById,
  trim,
  groupBy,
  urlParamStr,
  deepClone,
  showLoading,
  hideLoading,
  drawLine,
  drawCircle,
  uploadFile,

  isNumberByGe0,
  ciphertext,
  dateFormat,

  isIdCardNo,
  isPhoneNo,
  isEmailNo,
  isAllNumber,
  fileNameFromUrl,
  aesEncrypt,

  logout,
  getLoginedExpiresTime,

  pushByNewPage,

  upToInt,

  startsWith
}
